package com.ding.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ding.entity.Student;
import com.ding.service.Impl.StudentServiceImpl;
import com.ding.service.StudentService;
import com.ding.util.FileUtil;
import com.ding.util.Page;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "StudentServlet", urlPatterns = "/stu.action")
@MultipartConfig
public class StudentServlet extends HttpServlet {
    private static final Logger logger = Logger.getLogger(StudentServlet.class.getName());

    StudentService studentService = new StudentServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前台传递的数据
        logger.debug("opr:"+request.getParameter("opr"));
        logger.debug("stuName:"+request.getParameter("stuName"));
        String opr = (request.getParameter("opr") == null || "".equals(request.getParameter("opr")))
                ? "list" : request.getParameter("opr");
        switch (opr) {
            case "list":
                //获取查询条件
                String stuName = request.getParameter("stuName");

                String ClassId = request.getParameter("classId");
                //当前第几页
                String pageNum = request.getParameter("pageNum");

                Page<Student> page = new Page<>();

                page.setPageNum((pageNum == null || "".equals(pageNum)) ? 1 : Integer.parseInt(pageNum));

                //获取分页数据
                page = studentService.selectPage(page, stuName, Integer.parseInt(ClassId));

                //将数据转成json  传递給前台
                String json = JSON.toJSONString(page, SerializerFeature.WriteNullStringAsEmpty);
                response.getWriter().print(json);
                return;

            case "edit":
                //编辑
                editorStu(request, response);
                return;
            case "detail":
                //详情
                stuDetail(request, response);
                return;
            case "stuDetail":
                String id = request.getParameter("id");

                Student student = studentService.stuDetail(Integer.parseInt(id));

                request.setAttribute("student",student);
                request.getRequestDispatcher("/jsp/detail.jsp").forward(request,response);

                return;

            case "delStu":
                String dd = request.getParameter("id");
                int del = studentService.delStu(Integer.parseInt(dd));
                String j = JSON.toJSONString(del);
                response.getWriter().print(j);

        }

    }

    //学生详情
    private void stuDetail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");

        Student student = studentService.stuDetail(Integer.parseInt(id));

        String json = JSON.toJSONString(student, SerializerFeature.WriteNullListAsEmpty);

        response.getWriter().print(json);
    }

    //编辑学生
    private void editorStu(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Student student = new Student();
        logger.debug("id" + request.getParameter("stuId"));
        int stuId = (request.getParameter("stuId") == null || "".equals(request.getParameter("stuId")))
                ? -1 : Integer.parseInt(request.getParameter("stuId"));
        //修改
        student.setId(stuId);
        student.setUserName(request.getParameter("stuName"));
        student.setSex(request.getParameter("sex"));
        //指定上传路径
        String fileUploadUrl = this.getServletContext().getRealPath("upload/");
        logger.debug("指定上传路径" + fileUploadUrl);
        File file = new File(fileUploadUrl);
        //如果上传路径不存在，则创建新目录
        if (!file.exists()) {
            file.mkdir();
        }
        Part part = request.getPart("imageFile");
        //解析上传文件名
        String fileName = FileUtil.jxFileName(part);
        logger.debug("上传文件名：" + fileName);
        //将文件上传服务器
        part.write(fileUploadUrl + File.separator + fileName);
        student.setImgPath("upload/" + fileName);
        student.setBirthday(request.getParameter("birthday"));
        student.setClassId(Integer.parseInt(request.getParameter("classId")));
        student.setPhone(request.getParameter("phone"));
        student.setAddress(request.getParameter("address"));

        boolean flag = studentService.editStu(student);
        Map map = new HashMap();
        if (flag){
            map.put("code", "ok");
        }else {
            map.put("code", "error");
        }
        response.getWriter().print(JSON.toJSONString(map));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
